package com.xunqi.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xunqi.common.constant.ProductConstant;
import com.xunqi.product.dao.AttrAttrgroupRelationDao;
import com.xunqi.product.dao.AttrGroupDao;
import com.xunqi.product.dao.CategoryDao;
import com.xunqi.product.entity.AttrAttrgroupRelationEntity;
import com.xunqi.product.entity.AttrGroupEntity;
import com.xunqi.product.entity.ProductAttrValueEntity;
import com.xunqi.product.service.CategoryService;
import com.xunqi.product.vo.AttrGroupRelationVo;
import com.xunqi.product.vo.AttrRespVo;
import com.xunqi.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunqi.common.utils.PageUtils;
import com.xunqi.common.utils.Query;

import com.xunqi.product.dao.AttrDao;
import com.xunqi.product.entity.AttrEntity;
import com.xunqi.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    private AttrAttrgroupRelationDao relationDao;

    @Resource
    private AttrGroupDao attrGroupDao;

    @Resource
    private CategoryDao categoryDao;

    @Resource
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId, String type) {

        Integer pageNo = Integer.parseInt(params.get("page").toString());
        Integer pageSize = Integer.parseInt(params.get("limit").toString());
        String key = params.get("key")==null?"":params.get("key").toString();

        //属性判断
        int typeCode = "base".equalsIgnoreCase(type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode();

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params)
                ,new QueryWrapper());
        PageUtils pageUtils = new PageUtils(page);

        List<AttrRespVo> records = attrGroupDao.attrGroupCategoryList(typeCode,key,catelogId,pageNo-1,pageSize);
        pageUtils.setList(records);

        return pageUtils;
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        //保持基本數據
        this.save(attr);

        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId()!=null){
            //保存关联关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());
            relationDao.insert(relationEntity);
        }

    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo   respVo = attrGroupDao.attrGroupCategoryById(attrId);
//        分类信息
        List<Long>  catePath = categoryService.findCatelogPath(respVo.getCatelogId());
        respVo.setCatelogPath(catePath);

        return respVo;

    }
    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        if(attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //1、修改分组关联
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();

            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());

            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if(count>0){
                relationDao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
            }else{
                relationDao.insert(relationEntity);
            }
        }


    }

    @Override
    public List<AttrEntity> getRelation(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id",attrGroupId));

        List<Long> attrIds=entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        if (attrIds.size()>0){
            Collection<AttrEntity> attrEntities = this.listByIds(attrIds);
            return (List<AttrEntity>) attrEntities;
        }
        return null;
    }

    @Override
    public void deleteRelation(List<AttrGroupRelationVo> vos) {
        relationDao.deleteBatchRelation(vos);
    }


    /**
     * 获取当前分组没有关联的所有属性
     * @param params
     * @param attrGroupId
     * @return
     */
    @Override
    public PageUtils getNoRelation(Map<String, Object> params, Long attrGroupId) {
//        当前分组只能关联自己所属分类 的属性且没有别的分组引用
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);

        List<AttrGroupEntity> groupEntities = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", attrGroupEntity.getCatelogId()));
//        当前分类下的其他分组
        List<Long> collect = groupEntities.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        QueryWrapper<AttrAttrgroupRelationEntity> wrapperRelation = new QueryWrapper<>();

//        这些分组关联的属性
        if (collect.size()>0){
            wrapperRelation.in("attr_group_id", collect);
        }
        List<AttrAttrgroupRelationEntity> groupIds = relationDao.selectList(wrapperRelation);
        List<Long> attrIds = groupIds.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        if (groupIds.size()>0){
            //        从当前分类中移除这些属性
            wrapper.eq("catelog_id", attrGroupEntity.getCatelogId()).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()).notIn("attr_id", attrIds);
        }else {
            wrapper.eq("catelog_id", attrGroupEntity.getCatelogId()).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        }

         String key = params.get("key")==null?"":params.get("key").toString();
        if (!key.isEmpty()){
            wrapper.and(i -> i.eq("attr_id",key).or().like("attr_name",key));
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }


}